#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

using namespace std;

void Usage(string proc)
{
    cout << "Usage: " << proc << " serverip serverport"<< endl;
}

// ./udpclient serverip serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    string Ser_ip = argv[1];
    uint16_t Ser_proc = stoi(argv[2]);
    //1.创建struct sockaddr 
    
    struct sockaddr_in Server;
    bzero(&Server,sizeof(Server));

    Server.sin_family=AF_INET;
    Server.sin_port = htons(Ser_proc);
    Server.sin_addr.s_addr= inet_addr(Ser_ip.c_str());

    int _sockeid = socket(AF_INET,SOCK_DGRAM,0);
    if(_sockeid <0)
    {
        cout<<"Client is error "<<endl;
        exit(1);
    }

    char Buffer[1024];
    string message;

    socklen_t len = sizeof(Server);

    while(true)
    {
        cout<<"Please enter :";
        getline(cin,message);
        sendto(_sockeid,message.c_str(),sizeof(message)-1,0,(struct sockaddr*)&Server,len);


        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);

        ssize_t s = recvfrom(_sockeid, Buffer, sizeof(Buffer)-1, 0, (struct sockaddr*)&temp, &len);//接受&
        if(s > 0)
        {
            Buffer[s] = 0;
            cout << Buffer << endl;
        }
    }

    // client 要bind吗？要！只不过不需要用户显示的bind！一般有OS自由随机选择！
    // 一个端口号只能被一个进程bind，对server是如此，对于client，也是如此！
    // 其实client的port是多少，其实不重要，只要能保证主机上的唯一性就可以！
    // 系统什么时候给我bind呢？首次发送数据的时候


    close(_sockeid);
    return 0;
}